<?php
/*
 * @Author: zwx
 * @Date: 2024-06-27 16:14:55
 * @LastEditors: zwx
 * @LastEditTime: 2024-09-12 22:33:07
 * @Description:
 */

namespace app\apiadmin\command;

use app\common\utils\Curl;
use think\facade\Db;

class getToken
{
    /**
     * 企业微信Access_Token
     * @param $keys  存储token的字段名
     * @param $appid 程序appid
     * @param $appsecret   程序的密钥
     */
    public static function getQiYeWeiXinAccessToken()
    {
        //检测本地是否已经拥有access_token，并且检测access_token是否过期
        $accessToken = self::_checkQiYeWeiXinAccessToken();
        if ($accessToken === false) {
            $accessToken = self::_getQiYeWeiXinAccessToken();
            return $accessToken['access_token'];
        } else {
            return $accessToken['access_token'];
        }
    }

    /**
     * 聚水潭
     *
     * 聚水潭的accesstoken
     * @param $keys  存储token的字段名
     * @param $appid 程序appid
     * @param $appsecret   程序的密钥
     * @return error|string
     */
    private static function _getQiYeWeiXinAccessToken()
    {
        //app_key   a4a15e3640e24d8aaf60b07452d6c443
        //app_secret  287fe57a787d4098a7e9ca146b5fe3d7
        $token = unserialize(Db::table('xh_common')->where(array('keys' => 'qiyeweixin_token_' . env('qywx.corpid')))->find()['values']);
        $queryUrl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . env('qywx.corpid') . '&corpsecret=' . env('qywx.corpsecret'); //令牌

        $result = Curl::callWebServer($queryUrl, '', 'GET', true, true);
        // dump($result);
        // dump(111);
        if (!empty($result) && $result['errcode'] == 0) {
            $accessToken['access_token'] = $result['access_token'];
            $accessToken['expires_in'] = $result['expires_in'];
        } else {
            return $result; //出错啦
        }

        //我们把token保存在数据库中
        $accessToken['time'] = time();

        $data = [];
        $data['values'] = serialize($accessToken);

        if (!$token) {
            Db::table('xh_common')->insertGetId($data);
        }
        $where = [];
        $where['keys'] = 'qiyeweixin_token_' . env('qywx.corpid');

        Db::table('xh_common')->where($where)->save($data);

        return $result;
    }

    /**
     * 企业微信的ACCESS_TOKEN是否过期
     * access_token的有效期目前为2小时(7200秒)，需定时刷新。
     *  @param $keys  存储token的字段名
     * @return bool
     */
    private static function _checkQiYeWeiXinAccessToken()
    {
        $data = Db::table('xh_common')->where(array('keys' => 'qiyeweixin_token_' . env('qywx.corpid')))->find();
        if ($data) {
            $data = unserialize($data['values']);
            if ($data && time() - $data['time'] < 60 * 60) {
                return $data;
            }
        }
        return false;
    }
}
